package com.jci.vsd.activity.UserInfo;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jci.vsd.R;
import com.jci.vsd.activity.BaseActivity;
import com.jci.vsd.activity.LoginActivity;
import com.jci.vsd.adapter.PicFeedBackAdapter;
import com.jci.vsd.application.VsdApplication;
import com.jci.vsd.bean.PicBean;
import com.jci.vsd.bean.feedback.FeedBackBean;
import com.jci.vsd.bean.feedback.UploadFileBean;
import com.jci.vsd.network.control.FeedBackApiControl;
import com.jci.vsd.network.control.UploadProgressListener;
import com.jci.vsd.observer.CommonDialogObserver;
import com.jci.vsd.observer.RxHelper;
import com.jci.vsd.utils.ImageUtils;
import com.jci.vsd.utils.Loger;
import com.jci.vsd.utils.TimeUtils;
import com.jci.vsd.view.widget.SimpleToast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;

/**
 * Created by Administrator on 2017/11/15 0015.
 * 用户反馈
 */

public class UsersFeedBackActivity extends BaseActivity {
    @BindView(R.id.button_back)
    ImageButton backBtn;
    @BindView(R.id.textview_title)
    TextView titleTxt;
    @BindView(R.id.picGridView)
    GridView picGridView;
    @BindView(R.id.submitBtn)
    Button submitBtn;
    @BindView(R.id.feedBackTimeTxt)
    TextView feedbackTime;

    @BindView(R.id.feedBackThemeEdit)
    TextView edttitle;

    @BindView(R.id.feedBackEdit)
    EditText edtContent;

    private PicFeedBackAdapter picAdapater; //图片adapter
    private static final int PICK_PHOTO = 10002; //图片请求码
    List<PicBean> picBeanList = new ArrayList<>();//UI图片显示集合
    private ArrayList<String> selectedPhotos = new ArrayList<>();//选择图片集合
    private List<UploadFileBean> uploadFileBeans;//多图片上传成功集合

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_feed_back_layout);
        titleTxt.setText(getResources().getString(R.string.feed_back));
        uploadFileBeans = new ArrayList<>();
        initViewEvent();
        feedbackTime.setText(TimeUtils.getCurrentTime());
        picAdapater = new PicFeedBackAdapter(UsersFeedBackActivity.this, picBeanList);
        picGridView.setAdapter(picAdapater);
//        picGridView.setOnItemClickListener(this);
        picAdapater.setAddAndDeleteListener(new PicFeedBackAdapter.AddAndDeleteListener() {
            @Override
            public void addImag() {
                takePics();
            }

            @Override
            public void viewImag(int pos) {
                //看大图
            }

            @Override
            public void deletImg(int pos) {
                //删除

            }
        });

    }

    @Override
    protected void initViewEvent() {
        backBtn.setOnClickListener(this);
        submitBtn.setOnClickListener(this);

    }

    //数据检查
    private void checkdata() {
        String title = edttitle.getText().toString();
        String content = edtContent.getText().toString();
        String picsStr = "";
        if (uploadFileBeans != null && uploadFileBeans.size() > 0) {
            for (int i = 0; i < uploadFileBeans.size(); i++) {
                String uploadFileItemStr = uploadFileBeans.get(i).getOriginalUrl();
                Loger.e("--picuploadFileItemStr--" + uploadFileItemStr);
                if (TextUtils.isEmpty(picsStr)) {
                    picsStr = uploadFileItemStr;
                } else {
                    picsStr = picsStr + "," + uploadFileItemStr;
                }

            }
        }

        if (TextUtils.isEmpty(title) && TextUtils.isEmpty(content) && TextUtils.isEmpty(picsStr)) {
            SimpleToast.toastMessage("请填写反馈内容或是图片", Toast.LENGTH_SHORT);
            return;
        }
        Loger.e("--picStrs--" + picsStr);


        FeedBackBean feedBackBean = new FeedBackBean();
        feedBackBean.setFeedbackTitle(title);
        feedBackBean.setFendbackContent(content);
        feedBackBean.setPictureUrl(picsStr);

        submitFeedBack(feedBackBean);
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PICK_PHOTO:
                    getPicPathArray(data);
                    break;
                case PhotoPicker.REQUEST_CODE:
                case PhotoPreview.REQUEST_CODE:
                    setPics(data);
                    break;
                default:
                    break;

            }
        }
    }

    //图片设置
    private void setPics(Intent data) {

        if (data != null) {
            selectedPhotos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            picBeanList.clear();
            PicBean picBean;

            for (int i = 0; i < selectedPhotos.size(); i++) {
                picBean = new PicBean();
                picBean.setPhotoPath(selectedPhotos.get(i));
//                //0 是+ 非0 是图片
//                picBean.setStatus(1);
                picBeanList.add(picBean);
//                picAdapater.notifyDataSetChanged();
            }

            Loger.e("picBeanlist.size()=" + picBeanList.size());

            uploadPics(picBeanList);

        }
    }

    private void uploadPics(List<PicBean> list) {
        List<File> files = new ArrayList<>();
        File file;
        for (int i = 0; i < list.size(); i++) {
            file = new File(list.get(i).getPhotoPath());
            files.add(file);
        }

        subFile(files, uploadProgressListener);


    }

    private void submitFeedBack(FeedBackBean feedBackBean) {
        Observable<String> observable = new FeedBackApiControl().submitFeedBackContent(feedBackBean);
        CommonDialogObserver<String> observer = new CommonDialogObserver<String>(UsersFeedBackActivity.this) {
            @Override
            public void onNext(String s) {
                super.onNext(s);
                Loger.e("subFile" + s);
                JSONObject jsonObject = JSON.parseObject(s);
                //int code = jsonObject.getIntValue(AppConstant.JSON_CODE);
                String responseStr = jsonObject.getString("response");
                if (responseStr.equals("success")) {
                    SimpleToast.toastMessage("提交成功", Toast.LENGTH_SHORT);
                    finish();


                } else if (responseStr.equals("error")) {

                    SimpleToast.toastMessage("提交失败，请重试", Toast.LENGTH_SHORT);

                }

            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);

                if (t.getMessage().equals("401")) {
                    SimpleToast.toastMessage("登录超时，请重新登录", Toast.LENGTH_SHORT);
                    exit();
                    toActivity(LoginActivity.class);
                } else {
                    SimpleToast.toastMessage(t.getMessage(), Toast.LENGTH_SHORT);
                }
            }
        };
        RxHelper.bindOnUI(observable, observer);

    }


    private void subFile(List<File> files, UploadProgressListener uploadProgressListener) {
//        final File file = new File(path);
//        Loger.i("subFile = " + path);
        //  Observable<String> observable = new FeedBackApiControl().submitMultiPic(files, uploadProgressListener);
        Observable<String> observable = new FeedBackApiControl().submitMultiPic2(files, uploadProgressListener);
        CommonDialogObserver<String> observer = new CommonDialogObserver<String>(UsersFeedBackActivity.this) {
            @Override
            public void onNext(String s) {
                super.onNext(s);
                JSONObject jsonObject = JSON.parseObject(s);
                String responseStr = jsonObject.getString("response");
                if (responseStr.equals("success")) {
                    SimpleToast.toastMessage("图片上传成功", Toast.LENGTH_SHORT);

                    uploadFileBeans = JSON.parseArray(jsonObject.getString("data"), UploadFileBean.class);
                    picAdapater.notifyDataSetChanged();

                } else if (responseStr.equals("error")) {
                    SimpleToast.toastMessage("图片上传失败，请重试", Toast.LENGTH_SHORT);

                }

            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);

                if (t.getMessage().equals("401")) {
                    SimpleToast.toastMessage("登录超时，请重新登录", Toast.LENGTH_SHORT);
                    exit();
                    toActivity(LoginActivity.class);
                } else {
                    SimpleToast.toastMessage(t.getMessage(), Toast.LENGTH_SHORT);
                }
            }
        };
        RxHelper.bindOnUI(observable, observer);

    }


    private void takePics() {
        PhotoPicker.builder()
                .setPhotoCount(3)
                .setShowCamera(true)
                .setPreviewEnabled(false)
                .setSelected(selectedPhotos)
                .start(UsersFeedBackActivity.this);

    }

    //获取图片路径
    private List<PicBean> getPicPathArray(final Intent data) {
        Observable<Boolean> observable = Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
                //data中自带有返回的uri
                Uri photoUri = data.getData();
                //获取照片路径
                String[] filePathColumn = {MediaStore.Audio.Media.DATA};
                Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null);
                int index = 0;
                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                    String photoPath = cursor.getString(cursor.getColumnIndex(filePathColumn[index]));
                    Bitmap bitmap = ImageUtils.getImageThumbnail(photoPath, 200, 200);
                    PicBean picBean = new PicBean(1, bitmap);
                    picBean.setPhotoPath(photoPath);
                    picBeanList.add(picBeanList.size() - 1, picBean);
                }
                if (picBeanList.size() >= 10) {
                    picBeanList.remove(picBeanList.size() - 1);
                }
                cursor.close();
                e.onNext(true);
                e.onComplete();
            }
        });

        Observer<Boolean> observer = new CommonDialogObserver<Boolean>(UsersFeedBackActivity.this) {
            @Override
            public void onNext(Boolean aBoolean) {
                super.onNext(aBoolean);
                if (aBoolean) {
                    picAdapater.notifyDataSetChanged();
                }
            }
        };
        RxHelper.bindOnUI(observable, observer);


        return picBeanList;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        VsdApplication.getRefWatcher(this).watch(this);
    }

    @Override
    public void onClick(View view) {
        Loger.i("onclicl");
        super.onClick(view);
        switch (view.getId()) {
            case R.id.submitBtn:
                checkdata();
                break;
            default:
                break;
        }
    }


    UploadProgressListener uploadProgressListener = new UploadProgressListener() {
        @Override
        public void onProgress(long currentBytesCount, long totalBytesCount) {
            Loger.i("uploadProgressListener = " + currentBytesCount);
        }
    };
}
